# coding=utf-8
from django.contrib.auth.models import Group, User
from com.kjssoft.common import LOGGER
from com.kjssoft.eagleye.consts import EagleyeUserConsts
from com.kjssoft.eagleye.models import EEUser
from com.kjssoft.eagleye.social.models import Application

__author__ = 'daihaibin'

class EagleyeAuthMiddleware(object):

    def __init__(self):
        groups = Group.objects.filter(name=EagleyeUserConsts.Group.DEFAULT_USER_GROUP_NAME)
        if not groups.count():
            group = Group.objects.create(
                name = EagleyeUserConsts.Group.DEFAULT_USER_GROUP_NAME
            )
            group.save()
        else:
            group = groups[0]
        self.eeuser_group = group

    def process_request(self, request):
        user = request.user
        if user and isinstance(user, User):
            if user.is_authenticated():
                groups = user.groups.filter()
                if self.eeuser_group in groups:
                    #用户为EEUser
                    request.user = EEUser.objects.get(id = user.id)
        request.eeuser_group = self.eeuser_group

class EagleyeAppMiddleware(object):

    def process_request(self, request):
        app = request.GET.get('app')
        if app:
            app = str(app).strip().lower()
            try:
                app = Application.objects.get(name = app)
            except Application.DoesNotExist as e:
                LOGGER.error(e)
                app = None
        else:
            app = None
        request.app = app

